<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="Admin.css">
  <title>Document</title>
  <style>
    th,
    td {
      padding: 10px 20px;
      text-align: center;
    }

    #pre,
    #next {
      padding: 10px;
      cursor: pointer;
      color: #666;
      font-size: 25px;
    }

    #pre,
    #next,
    #pages {
      float: left;
    }

    #pages div {
      float: left;
      padding: 10px;
      margin: 0 10px;
      margin-top: 10px;
      cursor: pointer;
    }

    #xiugaikuang {
      position: absolute;
      top: 100px;
      left: 50%;
      padding: 20px;
      border: 1px solid red;
      background-color: gray;
      display: none;
    }
  </style>
</head>

<body>
  <form class="form-inline">
    <div class="form-group">
      <input type="text" class="form-control search" id="stuNames" placeholder="请输入管理员姓名">
    </div>
    <button type="submit" class="btn btn-info">搜索</button>
    <button type="reset" class="btn btn-info" onclick="reset()">重置</button>
    <button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal2">添加管理员</button>
  </form>

  <div id="mainDiv">
    <table class="table table-bordered table-hover">
      <thead>
        <tr>
          <th>编号</th>
          <th>姓名</th>
          <th>帐号</th>
          <th>类型</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>

      </tbody>
    </table>
    <!-- 修改Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="myModalLabel">修改管理员信息</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                aria-hidden="true">&times;</span></button>
          </div>
          <div class="modal-body">
            <!-- 表单 -->
            <form class="form-horizontal">
              <div class="form-group">
                <label for="stuId" class="col-sm-2 control-label">编号</label>
                <div class="col-sm-8 insert">
                  <input type="text" class="form-control" id="stuId" disabled>
                </div>
              </div>
              <div class="form-group">
                <label for="stuName" class="col-sm-2 control-label">姓名</label>
                <div class="col-sm-8">
                  <input type="text" class="form-control" id="stuName">
                </div>
              </div>
              <div class="form-group">
                <label for="stuUserId" class="col-sm-2 control-label">账号</label>
                <div class="col-sm-8">
                  <input type="text" class="form-control" id="stuUserId">
                </div>
              </div>
              <div class="form-group">
                <label for="stuUserId" class="col-sm-2 control-label">密码</label>
                <div class="col-sm-8">
                  <input type="text" class="form-control" id="stuPas">
                </div>
              </div>
              <div class="form-group">
                <label for="dormId" class="col-sm-2 control-label">类型</label>
                <div class="col-sm-8">
                  <select name="form-control" id="dormId">
                    <option value="1">管理员</option>
                    <option value="2">超级管理员</option>
                  </select>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" onclick="updateStu()">确定</button>
          </div>
        </div>
      </div>
    </div>


    <!-- 添加管理员 -->
    <div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="myModalLabel">添加管理员</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                aria-hidden="true">&times;</span></button>
          </div>
          <div class="modal-body">
            <!-- 表单 -->
            <form class="form-horizontal">
              <div class="form-group">
                <label for="stuName" class="col-sm-2 control-label">姓名</label>
                <div class="col-sm-8">
                  <input type="text" class="form-control" id="AdName">
                </div>
              </div>
              <div class="form-group">
                <label for="stuUserId" class="col-sm-2 control-label">账号</label>
                <div class="col-sm-8">
                  <input type="text" class="form-control" id="AdUser">
                </div>
              </div>
              <div class="form-group">
                <label for="stuUserId" class="col-sm-2 control-label">密码</label>
                <div class="col-sm-8">
                  <input type="text" class="form-control" id="AdPass">
                </div>
              </div>
              <div class="form-group">
                <label for="dormId" class="col-sm-2 control-label">类型</label>
                <div class="col-sm-8">
                  <select name="form-control" id="AdType">
                    <option value="1">管理员</option>
                    <option value="2">超级管理员</option>
                  </select>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" onclick="insertAdmin()">确定</button>
          </div>
        </div>
      </div>
    </div>
  </div>
  </div>
  </div>
  </div>





  <div class="page_wrap">
    <div id="pre">
      &lt;
    </div>
    <div id="pages">
      <!-- <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div> -->
    </div>
    <div id="next">&gt;</div>
  </div>
  </div>

  <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>
  <script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
  <script src="./utlis.js"></script>
  <script>
    //模拟假数据
    let student = [];

    let nowPage = 1;
    let maxPage;

    window.onload = function () {
      //获取本地存储的isLogin
      // let isLogin1 = localStorage.getItem('isLlogin');
      // let isLogin = getStorage('isLlogin');
      // let stu = sessionStorage.getItem('arrStu');

      // console.log(typeof JSON.parse(stu));
      // console.log(isLogin);
      //--------!!isLogin---------
      //--------!isLogin--->!"fasle"
      //------------------->!true--->false
      //-----------------------------!false-->true
      // if(isLogin){
      getStudent();
      // }else{
      //   location.href = 'day18-2.html'
      // }
    }
    //获取学生列表
    function getStudent() {
      //发送请求，获取学生数据
      $.ajax({
        url: 'http://47.109.16.231:3000/admin/getadmin',
        type: 'get',
        success: function (res) {
          console.log(res);
          student = res.data;
          //---------初始化
          showPage(student);
        }
      })
    }

    //动态渲染表格
    function showTbody(start, end, tbodyData) {
      $('#mainDiv>table>tbody').html('');
      //目的 --->往tbody中添加tr和td
      for (let i = start; i <= end; i++) {
        //判断是否是最后一页
        if (tbodyData.length > i) {
          $('#mainDiv>table>tbody').append(`
            <tr>
              <td>${tbodyData[i].id}</td>
              <td>${tbodyData[i].name}</td>
              <td>${tbodyData[i].userId}</td>
              <td>${tbodyData[i].type==1?'管理员':'超级管理员'}</td>
              <td>
                <button class="xiugai btn btn-primary" data-id=${tbodyData[i].id} data-toggle="modal" data-target="#myModal">修改</button>
                <button class="shanchu btn btn-default" data-id=${tbodyData[i].id} onclick="del()">删除</button>
              </td>
            </tr>
          `)
        }
      }
    }
    //渲染页码
    function showPage(stuData) {
      //知道有多少页---一页展示5条数据
      let pageNum = Math.ceil(student.length / 5);
      maxPage = pageNum;
      for (let i = 0; i < pageNum; i++) {
        //往pages中添加页码
        $('#pages').append(`<div>${i + 1}</div>`)
      }
      //渲染tbody
      showTbody(0, 4, stuData)
    }

    //-------------------------------------------------
    $('#next').click(function () {
      //渲染当前页的下一页的数据
      //知道当前页-----下一页 当前页++
      let page;
      nowPage < maxPage ? page = nowPage + 1 : page = nowPage;
      let start = (page - 1) * 5;
      let end = page * 5 - 1;
      showTbody(start, end, student);
      nowPage = page;
    })

    $('#pre').click(function () {
      //渲染当前页的上一页的数据
      //知道当前页-----上一页 当前页--
      let page;
      nowPage > 1 ? page = nowPage - 1 : page = nowPage;
      let start = (page - 1) * 5;
      let end = page * 5 - 1;
      showTbody(start, end, student);
      nowPage = page;
    })

    //--------页码翻页：事件委托----------
    $('#pages').on('click', 'div', function () {
      //渲染对应页号码的数据
      //1.1获取当前点击的页码
      let page = parseInt($(this).text());
      //1.2根据当前号码计算起始结束的位置
      let start = (page - 1) * 5;
      let end = page * 5 - 1;
      //1.3渲染表格
      showTbody(start, end, student);
      //1.4更新nowpage
      nowPage = page;
    })
    //-------------------修改
    let stuUpdate = {};
    $('tbody').on('click', '.xiugai', function () {
      //1.修改框显示
      $('#xiugaikuang').css({
        display: 'block'
      });
      //2.将当前的这条修改信息展示在我的div上（回显）
      let stuId = parseInt($(this).attr('data-id'));
      stuUpdate.id = stuId;
      //筛选器
      let mydata = student.filter(item => {
        return item.id === stuId
      })
      $('#stuId').val(mydata[0].id)
      $('#stuName').val(mydata[0].name)
      $('#stuUserId').val(mydata[0].userId)
      $('#stuPas').val(mydata[0].password)
      $('#dormId').val(mydata[0].type)
    })

    //修改功能
    function updateStu() {
      // console.log(stuUpdate);
      //1.获取表单数据
      let id = $('#stuId').val();
      let name = $('#stuName').val();
      let userId = $('#stuUserId').val();
      let password = $('#stuPas').val();
      let type = $('#dormId').val();
      // stuUpdate.stuId = stuId;
      stuUpdate = {
        ...stuUpdate,
        ...{
          id,
          name,
          userId,
          password,
          type
        }
      };
      // 2.发送请求，将数据给后台
      $.ajax({
        url: 'http://47.109.16.231:3000/admin/updateadmin',
        type: 'post',
        data: stuUpdate,
        success: function (res) {
          console.log(res);
          getStudent();
          $('#pages').html('')
          $('#myModal').modal('hide')
        }
      })
    }

    // 添加
    function insertAdmin() {
      //1.获取表单数据
      let name = $('#AdName').val();
      let userId = $('#AdUser').val();
      let password = $('#AdPass').val();
      let type = $('#AdType').val();
      console.log(stuId, stuName, stuUserId, stuPas);
      stuUpdate = {
        ...stuUpdate,
        ...{
          name,
          userId,
          password,
          type,
        }
      };
      $.ajax({
        url: 'http://47.109.16.231:3000/admin/addadmin',
        type: 'post',
        data: stuUpdate,
        success: function (res) {
          console.log(stuUpdate);
          console.log(res);
          $('#myModal2').modal('hide')
          $('#pages').html('')
          getStudent();
        }
      })
    }


    // 删除
    function del() {

    }
    $('tbody').on('click', '.shanchu', function () {

      let num = parseInt($(this).attr('data-id'));
      $.ajax({
        url: 'http://47.109.16.231:3000/admin/deladmin',
        type: 'post',
        data: {
          id: num
        },
        success: function (res) {
          console.log(res);
          $('#pages').html('')
          getStudent()
        }
      })

    })

    function reset() {
      $('#pages').html('')
      getStudent()
    }



    $('#querenxiugai').click(function () {
      //获取表单里的数据
      let obj = {
        id: parseInt($('#stuId').val()),
        name: $('#stuName').val(),
        sex: $('#stuSex').val(),
        age: $('#stuAge').val()
      }
      //讲这些数据和student数据中的对应那条互换（替换）
      for (let i = 0; i < student.length; i++) {
        if (student[i].id === obj.id) {
          student.splice(i, 1, obj);
        }
      }
      //清空表单，关闭div
      $('#stuId').val('')
      $('#stuName').val('')
      $('#stuSex').val('')
      $('#stuAge').val('')
      //属性表格
      let start = (nowPage - 1) * 5;
      let end = nowPage * 5 - 1;
      showTbody(start, end, student);
      $('#xiugaikuang').css({
        display: 'none'
      })
    })
    $('#quxiao').click(function () {
      $('#stuId').val('')
      $('#stuName').val('')
      $('#stuSex').val('')
      $('#stuAge').val('')
      $('#xiugaikuang').css({
        display: 'none'
      })
    })
  </script>
</body>

</html>